package com.retail.bbq.cola.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retail.bbq.cola.constant.RedisConstant;
import com.retail.bbq.cola.entity.ActivityUpcLevel;
import com.retail.bbq.cola.enums.ActivityUpcTypeEnum;
import com.retail.bbq.cola.enums.DeleteStatusEnum;
import com.retail.bbq.cola.service.ActivityUpcLevelService;
import com.retail.bbq.cola.mapper.ActivityUpcLevelMapper;
import com.retail.bbq.cola.vo.request.stampCollection.ActivityUpcLevelRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author jarvis.zhang
* @description 针对表【activity_upc_level(活动商品等级清单)】的数据库操作Service实现
* @createDate 2025-07-26 15:46:20
*/
@Service
@Slf4j
public class ActivityUpcLevelServiceImpl extends ServiceImpl<ActivityUpcLevelMapper, ActivityUpcLevel>
    implements ActivityUpcLevelService{

    @Resource
    private RedisTemplate redisTemplate;
    @Value("${api.client.id}")
    private String setupId;
    @Value("${lawson.happyBottle.logo}")
    private String happyBottleIconUrl;

    @Override
    public List<ActivityUpcLevel> getActivityUpcLevelList(ActivityUpcLevelRequest request) {
        String activityUpcLevelsRedisKey = String.format(RedisConstant.ACTIVITY_UPC_LEVELS_REDIS_KEY, request.getSetupId(), request.getMonth());
        log.info("明星产品key:{}", activityUpcLevelsRedisKey);
        Object result = redisTemplate.opsForValue().get(activityUpcLevelsRedisKey);
        if(Objects.nonNull(result) && CollectionUtils.isNotEmpty(JSONObject.parseArray(result.toString()))){
            log.info("明星产品value:{}", result.toString());
            return JSONObject.parseArray(result.toString(), ActivityUpcLevel.class);
        }
        List<ActivityUpcLevel> activityUpcLevels = baseMapper.selectList(new LambdaQueryWrapper<ActivityUpcLevel>()
                .eq(ActivityUpcLevel::getSetupId, request.getSetupId())
                .eq(ActivityUpcLevel::getMonth, request.getMonth())
                .eq(ActivityUpcLevel::getIsDel, DeleteStatusEnum.no_del.getCode()));
        redisTemplate.opsForValue().set(activityUpcLevelsRedisKey, JSONObject.toJSONString(activityUpcLevels), 10 , TimeUnit.MINUTES);
        return activityUpcLevels;
    }

    @Override
    public ActivityUpcLevel getActivityUpcInfo(String remark) {
        // 转换为带时区的 ZonedDateTime（默认系统时区）
        String defineTimeZone = "Asia/Shanghai";
        ZoneId zone = ZoneId.of(defineTimeZone);
        YearMonth yearMonth = YearMonth.now(zone);
        // 格式化为yyyyMM
        String month = yearMonth.toString().replace("-", "");
        //打印当前时区时间
        ZonedDateTime now = ZonedDateTime.now(zone);
        log.info("getActivityUpcInfo 当前时区:{},月份为:{},当前时区时间:{}", defineTimeZone, month, now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z")));
        return this.getActivityUpcInfoByMonth(remark, month);
    }

    @Override
    public ActivityUpcLevel getActivityUpcInfoByMonth(String remark, String month) {
        log.info("getActivityUpcInfoByMonth 当前查询月份为:{}", month);
        ActivityUpcLevelRequest request = new ActivityUpcLevelRequest(setupId, month);
        List<ActivityUpcLevel> activityUpcLevelList = this.getActivityUpcLevelList(request);
        if(CollectionUtils.isEmpty(activityUpcLevelList)){
            //返回兜底图标
            return happyBottle();
        }
        List<ActivityUpcLevel> todoList = activityUpcLevelList.stream()
                .filter(activityUpcLevel -> remark.toLowerCase().contains(activityUpcLevel.getUpcName().toLowerCase()))
                .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(todoList)){
            return happyBottle();
        }else if(todoList.size() == 1){
            return todoList.get(0);
        }else{
            return todoList.stream()
                    .max(Comparator.comparingInt(ActivityUpcLevel::getPriority)).get();
        }
    }

    private ActivityUpcLevel happyBottle() {
        ActivityUpcLevel happyBottle = new ActivityUpcLevel();
        happyBottle.setType(ActivityUpcTypeEnum.EFFECTIVE_GOODS.getCode());
        happyBottle.setUpcName("快乐瓶");
        happyBottle.setBrandIcon(happyBottleIconUrl);
        return happyBottle;
    }
}




